'use strict';

var _ = require('lodash');
var fs = require('fs');
var http = require('http');
var Share = require('./share.model');
var UploadPath = __dirname+'/../../../public';
var Timeline = require('../timeline/timeline.model');

// Get list of shares
exports.index = function(req, res) {
  Share.find().exec(function (err, shares) {
    if(err) { return handleError(res, err); }
    return res.json(200, shares);
  });
};

// Get a single share
exports.show = function(req, res) {
  Share.findById(req.params.id, function (err, share) {
    if(err) { return handleError(res, err); }
    if(!share) { return res.send(404); }
    return res.json(share);
  });
};

// Creates a new share in the DB.
exports.create = function(req, res) {
  var now = new Date();
  //return res.json(201, req.files);//你可能需要修改相关的newPath到你自己的地址
  console.log(req.body);
  var filePath = req.files.file.path;
  var upload_dir = UploadPath+'/assets/upload/' +now.getFullYear()+'-'+(now.getMonth()+1);
  fs.readdir(upload_dir, function(err, files){
    if(err){
      fs.mkdirSync(upload_dir, '0777');
      return console.log('不存在此目录');
    }
  });
  var uploadPath = "/assets/upload/" +now.getFullYear()+'-'+(now.getMonth()+1)+'/'+ req.files.file.name;
  var newPath = UploadPath + uploadPath;
  console.log(newPath);

  //把图片从临时文件夹复制到目的文件夹，当然最好删除临时文件
  fs.readFile(filePath, function (err, data) {
    if (err) {
      res.send(err);
      console.log('读取失败！');
      return;
    }

    fs.writeFile(newPath, data, function (err) {
      if (!err) {
        var newShare = {
          _user: JSON.parse(req.body.user),
          title: req.files.file.name,
          file_name: req.files.file.name,
          file_path: uploadPath,
          file_size: req.files.file.size/1024+'KB',
          file_type: req.files.file.type
        };
        var newTimeline = {
          _user:JSON.parse(req.body.user)._id,
          type: 'share',
          message: req.files.file.name
        };
        Timeline.create(newTimeline, function(err, timeline) {
          if(err) { return handleError(res, err); }
          console.log(timeline);
        });
        Share.create(newShare, function(err, share) {
          if(err) { return handleError(res, err); }
          return res.json(201, share);
        });
      } else {
        res.send(err);
        console.log('上传失败！');
      }
    });
  });
};

// Updates an existing share in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Share.findById(req.params.id, function (err, share) {
    if (err) { return handleError(res, err); }
    if(!share) { return res.send(404); }
    var updated = _.merge(share, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, share);
    });
  });
};

// Deletes a share from the DB.
exports.destroy = function(req, res) {
  Share.findById(req.params.id, function (err, share) {
    if(err) { return handleError(res, err); }
    if(!share) { return res.send(404); }
    fs.unlink(UploadPath+share.file_path);
    share.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

exports.weather = function (req, res) {
  var url = 'http://weatherapi.aliapp.com/?area=101210401';
  http.get(url, function(result) {
    var body = '';

    result.on('data', function(chunk) {
      body += chunk;
    });

    result.on('end', function() {
      var data = JSON.parse(body);
      return res.json(200, data);
    });
  }).on('error', function(e) {
    console.log("Got error: ", e);
  });
};

function handleError(res, err) {
  return res.send(500, err);
}
